// pages/habit_mine/habit_mine.js
var util=require('../../utils/util.js');

var sys = wx.getSystemInfoSync();
var windowWidth = sys.windowWidth;
var mW = sys.windowWidth * 0.85;
var mH = sys.windowHeight * 0.85;
var mdData = [['自然探索', 30], ['数理逻辑', 20], ['空间', 20], ['身体运动', 30], ['音乐', 40], ['人际', 50], ['内省', 90], ['语言', 50]];
var mData = [];
var mCount = mdData.length; //边数
var mCenter = ''; //中心点
var mRadius = ''; //半径(减去的值用于给绘制的文本留空间)
var mAngle = Math.PI * 2 / mCount; //角度
var mCtx = null;
var mColorPolygon = 'lightgray'; //多边形颜色
var mColorLines = 'lightgray'; //伞骨颜色
var mColorText = '#A4A4A4';//文字颜色
//var Interval = '';
//var lineInterval = '';
//var totalTime = 1000;//总执行时间
//var spaceTime = 10;//每隔多久执行一次
//var speed = spaceTime / totalTime;//每执行一次完成的进度百分比
var precent = 0;//当前完成的进度百分比
var precent2 = 0;
var lineprecent = 0;
var ctx1 = wx.createCanvasContext('radarcanvas1');
var ctx2 = wx.createCanvasContext('radarcanvas2');
var ctx3 = wx.createCanvasContext('radarcanvas3');
var ctx4 = wx.createCanvasContext('radarcanvas4');
var ctx5 = wx.createCanvasContext('radarcanvas5');
//var topText = ["帅气", "时尚", "典雅", "甜美", "自然", "浪漫", "文雅", "摩登"];
//var allSpaceTime = 50;//线程执行间隔时间

Page({

  data: {
    tab_one: false,
    tab_two: false,
    tab_three: true,
    time: [],
    check_day: [
      { status: [0, 0, 0, 0, 0, 0, 0] },
      { status: [0, 0, 0, 0, 0, 0, 0] },
      { status: [0, 0, 0, 0, 0, 0, 0] },
      { status: [0, 0, 0, 0, 0, 0, 0] },],
    title: 1,
    today:"",
    canvasW: mW * 2,
    canvasH: mH * 1.2,
    habit_list:[],
    days: ""
  },

  click: function (e) {
    var index1 = e.currentTarget.dataset.index1
    var index = e.currentTarget.dataset.index
    console.log(index1,index)
    var check_day = this.data.check_day
    console.log(check_day)
    check_day[index1].status[index] = !check_day[index1].status[index]
    console.log(check_day)
    this.setData({
      check_day: check_day
    })
  },
 
 myhabit: function(e) {
   console.log(e)
   var title = e.currentTarget.dataset.title
   this.setData({
     title: title
   })
  },

  switch_tab: function (e) {
    console.log(e)
    var tab = e.currentTarget.dataset.tab

    if (tab == "2") {
      wx.redirectTo({
        url: '../discovery/discovery',
      })
    }

    if (tab == "1") {
      var that = this
      wx.redirectTo({
        url: '../habit/habit',
      })
    }
  },

  history: function(e){
    console.log(e)
    wx.navigateTo({
      url: '../history/history'
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    function getWeek(i){
      var now = new Date();
      if(now.getDay() == 0) {
        var firstDay = new Date(now - 6 * 86400000);
      }
      else {
        var firstDay = new Date(now - (now.getDay() - 1) * 86400000);
      }
      firstDay.setDate(firstDay.getDate() + i);
      var mon = firstDay.getMonth() + 1;
      var day = firstDay.getDate();
    
      return mon + "-" + day
    }
    var that = this;
    var monday = getWeek(0);
    var tuesday = getWeek(1);
    var wednesday = getWeek(2);
    var thurday = getWeek(3);
    var friday = getWeek(4);
    var saturday = getWeek(5);
    var sunday = getWeek(6);

    var today = new Date();
    that.setData({
      time: [monday, tuesday, wednesday, thurday, friday, saturday, sunday],
      today: today.getDay(),
      habit_list: getApp().globalData.habit
    })
console.log(that.data.habit_list)

    var times = 0
    for(var i=0; i<that.data.habit_list.length; i++){
      times += that.data.habit_list[i].times
    }
    that.setData({
      days: times
    })


    wx.login({
      success: (res_code) =>{
        if(res_code.code){

    wx.request({
      url: getApp().globalData.my_server + "/minihabit/one_week_record",
      data: {
        code: res_code.code,
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        console.log(res.data.result)

        console.log(that.data.time)       
       console.log(that.data.habit_list);
        var i = 0, j = 0;
        that.data.habit_list.forEach((element) => {
         
        
          res.data.result.forEach((ele) =>{

            if(ele.name == element.name){   
              ele.dates.forEach((date) => {
                if (that.data.time.includes(date.substring(5))){
                  j = that.data.time.indexOf(date.substring(5));
                  var temp = "check_day[" + i + "].status.["+j+"]";
                  that.setData({
                    [temp] : 1,
                  });
                }
              });
            }
          });
         
          i++;

          //console.log(that.data.check_day)
        });
      },
      fail: function (res) {
        wx.showModal({
          title: '哎呀～',
          content: '读取失败',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
        console.log("fail!", res)
      },
      complete: function (res) {

      }
    
    });
    }else {
        console.log('登录失败！' + res.errMsg)
      }
      }
    });


    //雷达图
    var m = [];
    for (var i = 0; i < mCount; i++) {
      m[(i + 6) % mCount] = mdData[i];
    }
    mData = m;
    mCenter = this.rpx(mW); //中心点
    mRadius = mCenter - this.rpx(85); //半径(减去的值用于给绘制的文本留空间)

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    that.radarcanvas1();//雷达图文字+边框
   // that.clickCanvas();//调用画雷达图
  },
  // 单位转换
  rpx: function (param) {

    if (windowWidth == 0) {
      wx.getSystemInfo({
        success: function (res) {
          windowWidth = res.windowWidth;
        }
      });
    }
    return Number((windowWidth / 750 * param).toFixed(2));
  },
  // 绘制多边伞架
  drawPolygon: function (ctx) {
    ctx.save();
    ctx.setStrokeStyle(mColorPolygon);
    ctx.setLineDash([3, 3]);//虚线
    var r = mRadius / mCount; //单位半径
    //画8个圈
    for (var i = 0; i < mCount; i++) {
      ctx.beginPath();
      var currR = r * (i + 1); //当前半径
      //画8条边
      for (var j = 0; j < mCount; j++) {
        var x = mCenter + currR * Math.cos(mAngle * j);
        var y = mCenter + currR * Math.sin(mAngle * j);

        ctx.lineTo(x, y);
      }
      ctx.closePath()
      ctx.stroke();
      
    }
    
  },

  //绘制伞骨
  drawLines: function (ctx) {
    ctx.save();
    ctx.beginPath();
    ctx.setStrokeStyle(mColorLines);
    for (var i = 0; i < mCount; i++) {
      var x = mCenter + mRadius * Math.cos(mAngle * i);
      var y = mCenter + mRadius * Math.sin(mAngle * i);
      //var x = mCenter + mRadius * Math.cos(mAngle * i) * lineprecent;
      //var y = mCenter + mRadius * Math.sin(mAngle * i) * lineprecent;
      ctx.moveTo(mCenter, mCenter);
      ctx.lineTo(x, y);
    }
    ctx.closePath();
    ctx.stroke();
    ctx.draw();
    //var oldPrectet = lineprecent;
    //lineprecent = lineprecent + speed;
    //if (oldPrectet < 1 && lineprecent > 1) {
      //lineprecent = 1;
    //}
  },
  //绘制顶点文本
  drawText: function (ctx) {
    ctx.save();
    var fontSize = mCenter / 12 * 1;
    ctx.setFontSize(fontSize);
    ctx.setFillStyle(mColorText);
    for (var i = 0; i < mCount; i++) {
      var x = mCenter + mRadius * Math.cos(mAngle * i);
      var y = mCenter + mRadius * Math.sin(mAngle * i);
      //通过不同的位置，调整文本的显示位置
      if (mAngle * i >= 0 && mAngle * i < Math.PI / 2) {
        ctx.fillText(mData[i][0], x + 10, y + fontSize - 5);//3,4角
      } else if (mAngle * i == Math.PI / 2) {
        ctx.fillText(mData[i][0], x - 10, y + fontSize + 5);
      } else if (mAngle * i > Math.PI / 2 && mAngle * i <= Math.PI) {
        ctx.fillText(mData[i][0], x - 40 , y + fontSize - 10);//6,7角
      } else if (mAngle * i > Math.PI && mAngle * i <= Math.PI * 3 / 2) {
        ctx.fillText(mData[i][0], x - 30, y - 10);//1,8角
      } else {
        ctx.fillText(mData[i][0], x , y - 8);//2角
      }
    }
    
  },
  
  //绘制数据区域
  drawRegion: function (ctx, outColor) {
    ctx.save();
    ctx.beginPath();
    for (var i = 0; i < mCount; i++) {
      var x = mCenter + mRadius * Math.cos(mAngle * i) * mData[i][1] / 100;
      var y = mCenter + mRadius * Math.sin(mAngle * i) * mData[i][1] / 100;
      //var x = mCenter + mRadius * Math.cos(mAngle * i) * mData[i][1] / 100 * precent;
      //var y = mCenter + mRadius * Math.sin(mAngle * i) * mData[i][1] / 100 * precent;
      ctx.lineTo(x, y);
    }
    ctx.closePath();
    ctx.save();
    ctx.setFillStyle(outColor);
    //ctx.setGlobalAlpha(0.8);//透明度
    ctx.fill();
    ctx.draw(0, 0, 500, 500);
    //var oldPrectet = precent;
    //precent = precent + speed;
    //if (oldPrectet < 1 && precent > 1) {
      //precent = 1;
    //}
  },

//绘制数据点
  addDataPoint: function(ctx) {
    ctx.save();
    for (var i = 0; i < mCount; i++) {
      var x = mCenter + mRadius * Math.cos(mAngle * i) * mData[i][1]/100;
      var y = mCenter + mRadius * Math.sin(mAngle * i) * mData[i][1]/100;
      ctx.beginPath();
      ctx.arc(x, y, 3, 0, 2 * Math.PI);
      ctx.setFillStyle("rgba(183, 179, 156, 0.9)");
      ctx.fill();
      ctx.closePath();
    }
   ctx.draw();
  },
/** 
  //画雷达
  clickCanvas: function () {
    var that = this;
    precent = 0;
    precent2 = 0;
    lineprecent = 0;
    clearInterval(that.Interval);
    clearInterval(that.lineInterval);
    ctx1.clearRect(0, 0, mW, mH);
    ctx2.clearRect(0, 0, mW, mH);
    ctx3.clearRect(0, 0, mW, mH);
    ctx4.clearRect(0, 0, mW, mH);
    ctx5.clearRect(0, 0, mW, mH);
    var outColor = "rgba(228,215,182,0.8)";

    setTimeout(function () {//渐进画数据区域块
      that.Interval = setInterval(function () {
        if (precent <= 1) {
          that.drawRegion(ctx3, outColor);
        } else {
          clearInterval(that.Interval);
        }
      }, spaceTime - 20);
    }, 10);

    that.lineInterval = setInterval(function () {//渐进画伞骨
      if (lineprecent <= 1) {
        that.drawLines(ctx2);
        ctx2.draw(0, 0, 500, 500);
      } else {
        clearInterval(that.lineInterval);
      }
    }, spaceTime - 20);

    
   
  },*/

  radarcanvas1: function () {
    var that = this;
    const ctx1 = wx.createCanvasContext('radarcanvas1');
    precent = 0;
    lineprecent = 0;
    //var outColor = "rgba(228,215,182,0.8)";
    var outColor = "rgba(244,164,96,0.5)";
    that.drawPolygon(ctx1);//画伞架
    that.drawText(ctx1);//画文字
    that.drawLines(ctx2);
    ctx1.draw(0, 0, 500, 500);
   //ctx2.draw(0, 0, 500, 500);
    that.drawRegion(ctx3, outColor);
    that.addDataPoint(ctx4);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})